package com.mrli.cat.weather.activity;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Fragment;
import android.app.LoaderManager;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.Loader;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.mrli.cat.weather.R;
import com.mrli.cat.weather.database.WeatherContract;

public class ForecastFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> {
    private View mRoot;
    public static final String INIT_SHAREDPREFERENCE = "init";
    public static final String ACTION_LOCATION_DONE = "com.mrli.cat.action.main.fragment.location.done";
    public static final String ACTION_LOCATION_START = "com.mrli.cat.action.main.fragment.location.start";
    public static final String ACTION_LOCATION_FALSE = "com.mrli.cat.action.main.fragment.location.false";
    public static final String ACTION_SYNC_START = "com.mrli.cat.action.main.fragment.sync.start";
    public static final String ACTION_SYNC_DONE = "com.mrli.cat.action.main.fragment.sync.done";
    public static final String ACTION_SYNC_FALSE = "com.mrli.cat.action.main.fragment.sync.false";
    public static final String ACCOUNT_TYPE = "com.mrli.cat.account";
    public static final String ACCOUNT = "数据同步";
    private MainActivityReceiver mReceiver;
    private ForecastAdapter mAdapter;
    public static final int WEATHER_LOADER = 0x56CC;
    public static final String CITY_INFO = "city_info";

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        //注册监听器
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ACTION_LOCATION_START);
        intentFilter.addAction(ACTION_LOCATION_DONE);
        intentFilter.addAction(ACTION_LOCATION_FALSE);
        intentFilter.addAction(ACTION_SYNC_START);
        intentFilter.addAction(ACTION_SYNC_FALSE);
        intentFilter.addAction(ACTION_SYNC_DONE);
        mReceiver = new MainActivityReceiver();
        LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(getActivity());
        localBroadcastManager.registerReceiver(mReceiver, intentFilter);
        getLoaderManager().initLoader(WEATHER_LOADER, null, this);
        //检查网络
        ConnectivityManager connectivityManager =
                (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activiteNetwork = connectivityManager.getActiveNetworkInfo();
        boolean isConnected = activiteNetwork != null && activiteNetwork.isConnectedOrConnecting();
        if (!isConnected) {
            Toast.makeText(getActivity(), "当前网路环境较差", Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public View onCreateView(final LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) {
        mRoot = inflater.inflate(R.layout.fragment_forecast, null);
        mAdapter = new ForecastAdapter(getActivity(), null, 0);
        ListView listView = (ListView) mRoot.findViewById(R.id.forecast_list);
        listView.setAdapter(mAdapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Cursor cursor = (Cursor) parent.getItemAtPosition(position);
                if (cursor != null) {
                    Intent intent = new Intent(getActivity(), DetailActivity.class);
                    intent.putExtra(WeatherContract.WeatherEntry._ID, cursor.getInt(cursor.getColumnIndex(WeatherContract.WeatherEntry._ID)));
                    startActivity(intent);
                }
            }
        });
        Toolbar toolbar = (Toolbar) mRoot.findViewById(R.id.awesome_toolbar);
        toolbar.setTitle(getString(R.string.app_name));
        toolbar.inflateMenu(R.menu.menu_main);
        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.action_settings: {
                        Intent intent = new Intent(getActivity(), WeatherPreferenceActivity.class);
                        startActivity(intent);
                    }
                    return true;
                }
                return false;
            }
        });
        TextView location = (TextView) mRoot.findViewById(R.id.list_item_location);
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
        String city = sharedPreferences.getString(WeatherPreferenceActivity.LOCAL_CITY, "未知");
        location.setText(city);
        return mRoot;
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        //取消监听器
        LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(getActivity());
        localBroadcastManager.unregisterReceiver(mReceiver);
    }

    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
        switch (id) {
            case WEATHER_LOADER: {
                SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext());
                String cityName = sharedPreferences.getString(WeatherPreferenceActivity.LOCAL_CITY, "error");
                return new CursorLoader(getActivity(),
                        WeatherContract.WEATHER_CONTENT_URI.buildUpon().appendPath("cityName").appendPath(cityName).build(),
                        null,
                        null,
                        null,
                        null);
            }
        }
        return null;
    }

    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
        Log.d("查询结束", "数据条目" + data.getCount());
        mAdapter.swapCursor(data);
    }

    @Override
    public void onLoaderReset(Loader<Cursor> loader) {
        mAdapter.swapCursor(null);
    }


    /**
     * 当收到定位成功的消息, 开始数据同步
     */
    private class MainActivityReceiver extends BroadcastReceiver {
        private ProgressDialog mSyncStatusProgressDialog;

        @Override
        public void onReceive(final Context context, Intent intent) {
            if (intent.getAction().equals(ACTION_LOCATION_FALSE)) {
                Toast.makeText(getActivity(), "定位失败, 请手动选择城市", Toast.LENGTH_LONG).show();
            }
            if (intent.getAction().equals(ACTION_SYNC_START)) {
                mSyncStatusProgressDialog = new ProgressDialog(getActivity());
                mSyncStatusProgressDialog.setMessage("正在加载");
                mSyncStatusProgressDialog.setCancelable(false);
                mSyncStatusProgressDialog.show();
            }
            if (intent.getAction().equals(ACTION_SYNC_DONE)) {
                if (mSyncStatusProgressDialog != null) {
                    mSyncStatusProgressDialog.dismiss();
                }
                getLoaderManager().restartLoader(WEATHER_LOADER, null, ForecastFragment.this);
                TextView location = (TextView) mRoot.findViewById(R.id.list_item_location);
                SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
                String city = sharedPreferences.getString(WeatherPreferenceActivity.LOCAL_CITY, "未知");
                location.setText(city);
            }
            if (intent.getAction().equals(ACTION_SYNC_FALSE)) {
                if (mSyncStatusProgressDialog != null) {
                    mSyncStatusProgressDialog.dismiss();
                }
                Toast.makeText(getActivity(), "同步失败, 请检查网络链接", Toast.LENGTH_LONG).show();
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    public static Account CreateSyncAccount(Context context) {
        Account newAccount = new Account(ACCOUNT, ACCOUNT_TYPE);
        AccountManager accountManager = (AccountManager) context.getSystemService(context.ACCOUNT_SERVICE);
        if (accountManager.addAccountExplicitly(newAccount, null, null)) {

        } else {
            Log.d("Auth", "添加失败");
        }
        return newAccount;
    }

}
